// stores/appStore.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAppStore = defineStore('app', () => {
    // 状态
    const treeData = ref([])
    const userConfigers = ref([])
    const sentenceData = ref([])
    const inputData = ref({})

    // getters
    const hasTreeData = computed(() => treeData.value.length > 0)
    const hasUserConfigers = computed(() => userConfigers.value.length > 0)
    const hasSentenceData = computed(() => sentenceData.value.length > 0)

    // actions
    const setTreeData = (data) => {
        treeData.value = data
        // 持久化存储
        localStorage.setItem('treeData', JSON.stringify(data))
    }

    const setUserConfigers = (data) => {
        userConfigers.value = data
        localStorage.setItem('userConfigers', JSON.stringify(data))
    }
    const setSentenceData = (data) => {
        sentenceData.value = data
        localStorage.setItem('sentenceData', JSON.stringify(data))
    }

    const setInputData = (data) => {
        inputData.value = data
        localStorage.setItem('inputData', JSON.stringify(data))
    }

    // 从本地存储加载数据
    const loadFromStorage = () => {
        const storedTreeData = localStorage.getItem('treeData')
        const storedUserConfigers = localStorage.getItem('userConfigers')
        const storedSentenceData = localStorage.getItem('sentenceData')
        const storedInputData = localStorage.getItem('inputData')

        if (storedTreeData) treeData.value = JSON.parse(storedTreeData)
        if (storedUserConfigers) userConfigers.value = JSON.parse(storedUserConfigers)
        if (storedSentenceData) userConfigers.value = JSON.parse(storedSentenceData)
        if (storedInputData) inputData.value = JSON.parse(storedInputData)
    }

    // 清除所有数据
    const clearAllData = () => {
        treeData.value = []
        userConfigers.value = []
        sentenceData.value = []
        inputData.value = {}
        localStorage.removeItem('treeData')
        localStorage.removeItem('sentenceData')
        localStorage.removeItem('userConfigers')
        localStorage.removeItem('inputData')
    }

    return {
        // 状态
        treeData,
        userConfigers,
        inputData,
        sentenceData,
        // getters
        hasTreeData,
        hasUserConfigers,
        hasSentenceData,


        // actions
        setTreeData,
        setUserConfigers,
        setSentenceData,
        setInputData,
        loadFromStorage,
        clearAllData
    }
})